<?php
/**
 * 微信公众平台相应操作响应控制器
 *
 * @package    app
 * @version    1.0
 * @author     Ray 33705910@qq.com
 * @license    MIT License
 * @copyright  2013 - 2015 Ray
 * @link       http://wangxiaolei.cn
 */

/**
 * @package  app
 * @extends  Controller
 */
class Controller_WXApi extends Controller{

	public function action_index(){
	}

	/**
	* 微信基础token操作 
	*
	* @param
	* @return
	*/
	public function action_token(){}

	/**
	* 微信模板消息操作
	* 
	* @param
	* @return
	*/
	public function action_msg_tpl(){

	}


	/**
	* 微信接入
	* @return
	*/
	public function action_action($account_id = 0){

		if( ! $account_id){
			die('无效的参数');
		}

		$account = \Model_WXAccount::find($account_id);
		if( ! $account){
			die('非法请求');
		}

		//检验消息是否合法
		if( ! \tools\WechatTools::checkSignature(\Input::get('signature', false), \Input::get('timestamp', false), \Input::get('nonce', false), $account->token)){
			die('非法请求');
		}

		//接入请求
		if(\Input::get('echostr', false)){
			if($account->status != 'NONE'){
				die('公众帐户未被允许接入');
			}else{
				die(\Input::get('echostr'));
			}
		}

		//其它请求
		$post = $GLOBALS["HTTP_RAW_POST_DATA"];
		if( ! $post){
			die('');
		}
		
		//存储公众帐户信息
		\Session::set('WXAccount', $account);

		$data = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
		$wechat = new \tools\Wechat($data);
		$wechat->handle();
	}

	/**
	* OAuth2转入
	*/
	public function action_oauth2_callback(){
		$data = \Input::get();
		if( ! isset($data['code']) || ! $data['code']){
			die('无效的参数');
		}
		
		$open_id = $this->get_openid($data);
		
		if( ! $open_id){
			die('无效的参数');
		}
		$url = \Model_WXAccountUrl::find($data['state']);
		if(! $url){
			die('无效状态');
		}
		\Response::redirect($url->url);
	}
	
	/**
	* 获取OPENID
	* @param $data 
	*/
	private function get_openid($data){
		\Config::load('wechat');
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . \Config::get('AppID') . "&secret=" . \Config::get('AppSecret') . "&code={$data['code']}&grant_type=authorization_code";
		$curl = \Request::forge($url, 'curl');
		$curl->set_option(CURLOPT_SSL_VERIFYPEER, false);
		$curl->set_method('GET');
		$curl->set_options(array(
				CURLOPT_TIMEOUT => 30,
    			CURLOPT_FOLLOWLOCATION => true,
			)
		);
		$result = $curl->execute()->response();
		$params = json_decode($result);

		if(isset($params->openid)){
			return $params->openid;
		}else{
			return false;
		}
	}

	/**
	* 获取用户信息
	* @param $data 
	*/
	private function get_userinfo(){

	}
	
}